package com.qianxx.view.loadingview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.view.View;

import com.qianxx.base.R;

/**
 * Created by Administrator on 2017/9/21.
 */
public class RingLoading extends View {

    private int mRingWidth = 7;
    private int mRingStartColor = 0xfff99359;
    private int mRingEndColor = 0x00f5a623;

    private Paint mPaint;

    private int[] mGradientColor;
    private RectF mRectF;

    private float mCurrentAngle = 0;
    private int mWidth;
    private int mHeight;

    public RingLoading(Context context) {
        this(context, null);
    }

    public RingLoading(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RingLoading(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RingLoading);
        mRingStartColor = typedArray.getColor(R.styleable.RingLoading_ring_start_color, mRingStartColor);
        mRingEndColor = typedArray.getColor(R.styleable.RingLoading_ring_end_color, mRingEndColor);
        mRingWidth = typedArray.getDimensionPixelOffset(R.styleable.RingLoading_ring_width, dp2px(context, mRingWidth));
        typedArray.recycle();

        mGradientColor = new int[]{mRingStartColor, mRingEndColor};

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(mRingWidth);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w / 2;
        mHeight = h / 2;

        mRectF = new RectF(mRingWidth, mRingWidth, w - mRingWidth, h - mRingWidth);
        mPaint.setShader(new SweepGradient(mWidth, mHeight, mGradientColor, null));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.rotate(-mCurrentAngle, mWidth, mHeight);
        if (mCurrentAngle >= 360f) {
            mCurrentAngle = mCurrentAngle - 360f;
        } else {
            mCurrentAngle = mCurrentAngle + 2f;
        }
        canvas.drawArc(mRectF, 0, 360, false, mPaint);

        invalidate();
    }

    public int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public void setRingColor(int ringStartColor, int ringEndColor) {
        mRingStartColor = ringStartColor;
        mRingEndColor = ringEndColor;
        mCurrentAngle = 0;
        mGradientColor = new int[]{mRingStartColor, mRingEndColor};
        mPaint.setShader(new SweepGradient(mWidth, mHeight, mGradientColor, null));
        invalidate();
    }
}
